$(function () {
    obj.init();
});
var obj =new function () {
    'use strict';
    return {
        bookId:null,
        type:null,
        existBookId:null,
        applyId:null,
        form:null,
        demoModel:null,
        scheduleApplyId:null,
        init:function () {
            this.bookId  = xhTool.getQuery('bookId');
            this.type  = xhTool.getQuery('type');
            this.applyId  = xhTool.getQuery('id');
            this.existBookId  = xhTool.getQuery('existBookId');
            this.scheduleApplyId  = xhTool.getQuery('scheduleApplyId');
            this.form = new xhForm($('#apply_Plan_form'));
            this.funObj().addDate();
            this.listener();
        },
        listener:function () {
            var  $this = this;
            var xh_form = $('#apply_Plan_form');
            //添加申请
            $('#addApplyPlan').click(function () {
                $this.funObj().addApplyPlanAction();
            });
            //保存按钮
            $('#plan_form',window.top.document).find('[id="plan_form_confirm"]').click(function () {
                $this.funObj().saveApplyPlanForm();
            });
            //保存按钮
            $('#schedule_form',window.top.document).find('[id="schedule_form_confirm"]').click(function () {
                $this.funObj().saveApplyPlanForm();
            });
            //通过
            xh_form.on('click','[id^="checkTrue_"]',function () {
                var id = $(this).attr("id").split("checkTrue_")[1];
                $this.funObj().checkTrue(id);
            });
            //不通过
            xh_form.on('click','[id^="checkFalse_"]',function () {
                var id = $(this).attr("id").split("checkFalse_")[1];
                $this.funObj().checkFalse(id);
            });
            //取消
            xh_form.on('click','[id^="checkDel_"]',function () {
                var id = $(this).attr("id").split("checkDel_")[1];
                $this.funObj().checkDel(id);
            });
            //查看不通过原因
            xh_form.on('click','.reason',function () {
                var reason = $(this).attr('reasonMsg');
                window.top.xhTop.showMessage({
                    title: '[原因详情]',
                    text: reason
                });
            });
            //查看取消原因
            xh_form.on('click','.cancel',function () {
                var cancel = $(this).attr('cancelMsg');
                window.top.xhTop.showMessage({
                    title: '[原因详情]',
                    text: cancel
                });
            });
            //添加章节
            xh_form.on('click','[id^="addPlanCateLogs_"]',function () {
                var id = $(this).attr("id").split("addPlanCateLogs_")[1];
                $this.funObj().addCateLogs(id);
            });
            $('#addPlanCateLogs').click(function () {
                $this.funObj().addCateLogs();
            });
            $("#bookIdArr").on("select2:select",function(e){
                $this.funObj().selectBookId(e.params.data.id);
            });
            $('#selectBookId').on('change keyup', function () {
                $this.funObj().selectBookId($('#selectBookId').val());
            });
        },
        funObj:function () {
            var $this = this;
            var xh_form = $('#apply_Plan_form');
            return {
                addDate: function () {
                    $(".form-date").datetimepicker({
                        format: 'yyyy-mm-dd',
                        language: 'zh-CN',
                        minView: "month",
                        autoclose: true
                    });
                    $("#bookIdArr").select2({
                        ajax: {
                            url:  "bookIdsByNameKey",
                            dataType: 'json',
                            delay: 250,
                            data: function (params) {
                                return {
                                    key: params.term // 函数的参数
                                };
                            },
                            processResults: function (data, params) {
                                return {
                                    results: data
                                };
                            },
                            cache: true
                        },
                        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                        minimumInputLength: 1
                    });
                },
                addApplyPlanAction : function () {
                    $this.demoModel = $('.listCopyTd').eq(0).clone();
                    var dom = $($this.demoModel.clone());
                    $('.listCopyTd:last').after(dom);
                    var index = $('.listCopyTd').length - 1 ;
                    // dom.find('[name="addPlanList[0][id]"]').attr('name','addPlanList['+index+'][id]');
                    dom.find('[name="addPlanList[0][progress]"]').attr('name','addPlanList['+index+'][progress]');
                    dom.find('[name="addPlanList[0][demand][]"]').attr('name','addPlanList['+index+'][demand][]').select2({placeholder: '选择章节,必填',allowClear: false, multiple : true});
                    // dom.find('[name="addPlanList[0][startDate]"]').attr('name','addPlanList['+index+'][startDate]');
                    // dom.find('[name="addPlanList[0][endDate]"]').attr('name','addPlanList['+index+'][endDate]');
                    dom.find('[name="addPlanList[0][realStartDate]"]').attr('name','addPlanList['+index+'][realStartDate]');
                    dom.find('[name="addPlanList[0][realEndDate]"]').attr('name','addPlanList['+index+'][realEndDate]');
                    dom.find('[id="addPlanCateLogs_0"]').attr('id','addPlanCateLogs_'+index);
                    dom.show();

                    dom.find('[class="form-date form-control"]').datetimepicker({
                        format: 'yyyy-mm-dd',
                        language: 'zh-CN',
                        minView: "month",
                        autoclose: true
                    });

                    // var div = $('#applyPlanList');
                    // var aaa = $('#aaaa', parent.document);
                    // var height = div.height();console.log(height);
                    // aaa.scrollTop(800);
                    // console.log(aaa);
                    // // aaa.scrollTop = div.scrollHeight;
                    // // console.log(div.height());
                },
                checkTrue: function (id) {
                    xhExtra.askChangeStatus('res/checkTrueApplyPlan', {id:id}, null, '确认同意？', function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        location.reload();
                        xhExtra.setBtnNormal($('#plan_form',window.top.document).find('[id="plan_form_confirm"]'));
                        xhExtra.setBtnNormal($('#schedule_form',window.top.document).find('[id="schedule_form_confirm"]'));
                    });
                },
                checkFalse: function (id) {
                    // window.top.swal({
                    //     showCancelButton: true,
                    //     confirmButtonText: '确认',
                    //     cancelButtonText: '取消',
                    //     showLoaderOnConfirm: true,
                    //     allowOutsideClick: false,
                    //     title: '填写原因',
                    //     html: '<div><textarea type="text" id="reason" class="swal2-textarea" placeholder="必填"></textarea></div>',
                    //     preConfirm: function() {
                    //         return new Promise(function (resolve, reject) {
                    //             var reason = $('#reason', window.top.document).val();
                    //             if(!reason){
                    //                 reject('请填写原因');
                    //             } else {
                    //                 xhExtra.ajaxRequest('res/checkFalseApplyPlan', {
                    //                     id: id,
                    //                     reason: reason
                    //                 }, {success: true});
                    //                 resolve();
                    //                 location.reload();
                    //                 xhExtra.setBtnNormal($('#plan_form',window.top.document).find('[id="plan_form_confirm"]'));
                    //                 xhExtra.setBtnNormal($('#schedule_form',window.top.document).find('[id="schedule_form_confirm"]'));
                    //             }
                    //         })
                    //     }
                    // });

                    window.top.swal({
                        title: '填写原因',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        confirmButtonText: '确认',
                        allowOutsideClick: true,
                        showCloseButton: true,
                        showLoaderOnConfirm: true,
                        html: '<div><textarea type="text" id="reason" class="swal2-textarea" placeholder="必填"></textarea></div>',
                    }).then(function(isConfirm) {
                        var reason = $('#reason', window.top.document).val();
                        if(!reason){
                            alert('请填写原因');
                            return false;
                        } else {
                            xhExtra.ajaxRequest('res/checkFalseApplyPlan', {
                                id: id,
                                reason: reason
                            }, {success: true});
                            location.reload();
                            xhExtra.setBtnNormal($('#plan_form',window.top.document).find('[id="plan_form_confirm"]'));
                            xhExtra.setBtnNormal($('#schedule_form',window.top.document).find('[id="schedule_form_confirm"]'));
                        }
                    }, function(dismiss) {
                    });

                },
                checkDel: function (id) {
                    // xhExtra.askChangeStatus('res/delApplyPlan', {id:id}, null, '确认删除？', function (res) {
                    //     window.top.xhTop.showSuccess(res.msg);
                    //     location.reload();
                    //     xhExtra.setBtnNormal($('#plan_form',window.top.document).find('[id="plan_form_confirm"]'));
                    //     xhExtra.setBtnNormal($('#schedule_form',window.top.document).find('[id="schedule_form_confirm"]'));
                    // });

                    // window.top.swal({
                    //     showCancelButton: true,
                    //     confirmButtonText: '确认',
                    //     cancelButtonText: '取消',
                    //     showLoaderOnConfirm: true,
                    //     allowOutsideClick: false,
                    //     title: '填写原因',
                    //     html: '<div><textarea type="text" id="reason" class="swal2-textarea" placeholder="必填"></textarea></div>',
                    //     preConfirm: function() {
                    //         return new Promise(function (resolve, reject) {
                    //             var reason = $('#reason', window.top.document).val();
                    //             if(!reason){
                    //                 reject('请填写原因');
                    //             } else {
                    //                 xhExtra.ajaxRequest('res/delApplyPlan', {
                    //                     id: id,
                    //                     reason: reason
                    //                 }, {success: true});
                    //                 resolve();
                    //                 location.reload();
                    //                 xhExtra.setBtnNormal($('#plan_form',window.top.document).find('[id="plan_form_confirm"]'));
                    //                 xhExtra.setBtnNormal($('#schedule_form',window.top.document).find('[id="schedule_form_confirm"]'));
                    //             }
                    //         })
                    //     }
                    // });
                    window.top.swal({
                        title: '填写原因',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        confirmButtonText: '确认',
                        allowOutsideClick: true,
                        showCloseButton: true,
                        showLoaderOnConfirm: true,
                        html: '<div><textarea type="text" id="reason" class="swal2-textarea" placeholder="必填"></textarea></div>'
                    }).then(function(isConfirm) {
                        var reason = $('#reason', window.top.document).val();
                        if(!reason){
                            alert('请填写原因');
                            return false;
                        } else {
                            xhExtra.ajaxRequest('res/delApplyPlan', {
                                id: id,
                                reason: reason
                            }, {success: true});
                            location.reload();
                            xhExtra.setBtnNormal($('#plan_form',window.top.document).find('[id="plan_form_confirm"]'));
                            xhExtra.setBtnNormal($('#schedule_form',window.top.document).find('[id="schedule_form_confirm"]'));
                        }
                    }, function(dismiss) {
                    });
                },
                saveApplyPlanForm:function () {
                    var params = {};
                    if ($this.type === '1') {
                        params = {type:$this.type,bookId:$this.bookId,applyId:$this.applyId};
                    } else if ($this.type === '2'){
                        params = {type:$this.type,bookId:$this.bookId};
                    } else if ($this.type === '3'){
                        params = {type:$this.type,bookId:$this.bookId, existBookId:$this.existBookId};
                    } else if ($this.type === '4'){
                        params = {type:$this.type,bookId:$this.bookId, applyId: $this.scheduleApplyId, existBookId:$this.existBookId};//教辅计划页面,applyId为内部申请id
                    }
                    $this.form.submit('res/saveApplyPlanData',params,function (res) {
                        xhExtra.setBtnNormal($('#plan_form',window.top.document).find('[id="plan_form_confirm"]'));
                        xhExtra.setBtnNormal($('#schedule_form',window.top.document).find('[id="schedule_form_confirm"]'));
                        if(xhExtra.checkError(res)){
                            return false;
                        }
                        window.top.xhTop.showSuccess(res.msg);
                        $('#plan_form', window.top.document).find('[id="bt_modal_close"]').click();
                        $('#schedule_form', window.top.document).find('[id="bt_modal_close"]').click();
                        // window.top.xhTop.closeModal();
                        window.top.xhTop.getActiveFrame().obj.dataGrid.reload();
                    },{check:false})
                },
                addCateLogs: function (id) {
                    if ($this.type === '3' || $this.type === '4') {
                        window.top.xhTop.showModal({
                            title: '章节信息',
                            id: 'schedule_cate_log_form',
                            footerHtml:
                            '<button type="button" class="btn btn-primary xh-btn-load" id="schedule_cate_log_confirm">确认</button>' +
                            '<button type="button" class="btn btn-default" data-dismiss="modal" id="bt_modal_close">关闭</button>',
                            content: xhTool.getFrameString('res/showPlanCateLogTree', {type: $this.type, id: id, bookId: $this.bookId}, 500),
                            size: 'lg',
                            width:'950'
                        });
                    } else {
                        window.top.xhTop.showModal({
                            title: '章节信息',
                            id: 'plan_cate_log_form',
                            footerHtml:
                            '<button type="button" class="btn btn-primary xh-btn-load" id="plan_cate_log_confirm">确认</button>' +
                            '<button type="button" class="btn btn-default" data-dismiss="modal" id="bt_modal_close">关闭</button>',
                            content: xhTool.getFrameString('res/showPlanCateLogTree', {type: 2, id: id, bookId: $this.bookId}, 500),
                            size: 'lg',
                            width:'950'
                        });
                    }
                },
                addCateLog: function (cateLogData, id) {
                    xh_form.find('[name="addPlanList[' + id + '][demand][]"]').val(cateLogData).trigger('change');
                },
                addId: function (key) {
                    xhExtra.ajaxRequest('res/bookIdsByNameKey', {key: key}, {check:true}, function (data) {
                        $('#bookIdArr').empty().select2({placeholder: '选择书id', data: data, allowClear: true});
                    });
                    var selectId = $('#bookIdArr').val();
                },
                selectBookId: function (id) {
                    $this.bookId = id;
                    $('#selectBookId').val(id);
                    var cateLogsArr = [];
                    var indexArr = [];
                    var selectArr = [];
                    xhExtra.ajaxRequest('res/getCateLogsByBookId', {bookId: id}, {check:true,async:false}, function (data) {
                        cateLogsArr = data;
                    });
                    xh_form.find('[name^="addPlanList["]').each(function () {
                        var afterStr = $(this).attr("name").split("addPlanList[")[1];
                        var index = afterStr.split("]")[0];
                        var indexKey = $.inArray(index, indexArr);
                        if (indexKey < 0) {
                            indexArr.push(index);
                        }
                    });
                    if (JSON.stringify(indexArr) !== '[]') {
                        $.each(indexArr, function(id, index){
                            if (index == 0) {
                                var str = '';
                                $.each(cateLogsArr, function (value, text) {
                                    str += '<option value="'+value+'">'+text+'</option>';
                                });
                                xh_form.find('[name="addPlanList['+index+'][demand][]"]').empty().append($(str));
                            } else {
                                var str = '';
                                $.each(cateLogsArr, function (value, text) {
                                    str += '<option value="'+value+'">'+text+'</option>';
                                });
                                xh_form.find('[name="addPlanList['+index+'][demand][]"]').empty().append($(str)).select2({placeholder: '选择章节,必填', allowClear: false, multiple : true});
                            }
                            // xh_form.find('[name="addPlanList['+index+'][id]"]').value();
                            xh_form.find('[name="addPlanList['+index+'][progress]"]').val('');
                            // xh_form.find('[name="addPlanList['+index+'][startDate]"]').val('');
                            // xh_form.find('[name="addPlanList['+index+'][endDate]"]').val('');
                            xh_form.find('[name="addPlanList['+index+'][realStartDate]"]').val('');
                            xh_form.find('[name="addPlanList['+index+'][realEndDate]"]').val('');
                            xh_form.find('[id="addPlanCateLogs_'+index+'"]');
                        });
                    }
                }
            }
        }
    }
};
